package com.itheima.leetcode;

import com.itheima.queue.LinkedListQueue;

import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树Z字形层序遍历
 *
 * @FileName E01LeetCode103
 * @Description
 * @Author Sword
 * @date 2025-05-13
 **/
public class E01LeetCode103 {

    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        //结果集合
        List<List<Integer>> result = new LinkedList<>();

        if (root == null) {
            return result;
        }

        //队列
        LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);

        int c1 = 1; //当前层节点数
        boolean odd = true; //奇数层

        while (!queue.isEmpty()) {

            int c2 = 0; //下层节点数
            LinkedList<Integer> level = new LinkedList<>(); //保存每层结果
            for (int i = 0; i < c1; i++) {
                TreeNode n = queue.poll();
                //奇数尾插 偶数头插
                if (odd) {
                    level.offerLast(n.val);
                } else {
                    level.offerFirst(n.val);
                }

                if (n.left != null) {
                    queue.offer(n.left);
                    c2++;
                }

                if (n.right != null) {
                    queue.offer(n.right);
                    c2++;
                }
            }
            odd = !odd;
            result.add(level);
            c1 = c2;
        }
        return result;
    }

    /*
                1
               / \
              2   3
             /\   /\
            4  5 6  7
           / \
          8   9

          1
          3 2
          4 5 6 7
          9 8

     */

    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(
                        new TreeNode(4),
                        2,
                        new TreeNode(5)
                ),
                1,
                new TreeNode(
                        new TreeNode(5),
                        3,
                        new TreeNode(6)
                )
        );

        List<List<Integer>> lists = zigzagLevelOrder(root);
        System.out.println(lists);
    }
}
